package com.min.main.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.min.common.util.ShiroUtils;
import com.min.main.constant.UserConst;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.min.main.entity.RoleUserEntity;
import com.min.main.dao.RoleUserDao;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色对应表
 *
 * @author fengt
 * @date 2021-06-23 11:41:08
 */
@Service
public class RoleUserService extends ServiceImpl<RoleUserDao, RoleUserEntity> {

    public List<Long> getRoleIds(Long userId) {
        return this.listObjs(
                Wrappers.lambdaQuery(RoleUserEntity.class)
                        .select(RoleUserEntity::getRoleId)
                        .eq(!UserConst.SUPER_USERS.contains(userId), RoleUserEntity::getUserId, userId),
        c->Long.parseLong(c.toString()));
    }

    public boolean saveRoleUser(Long userId, List<Long> roleIdList) {
        if (roleIdList != null) {
            this.remove(Wrappers.lambdaQuery(RoleUserEntity.class).eq(RoleUserEntity::getUserId, userId));
            if (!roleIdList.isEmpty()) {
                final List<RoleUserEntity> entities = roleIdList.stream()
                        .map(m -> {
                            return new RoleUserEntity(userId, m);
                        })
                        .collect(Collectors.toList());
                return this.saveBatch(entities);
            }
        }
        return false;
    }

    /**
     * 检查配置角色边界（添加的角色项不能超过当前用户已拥有的角色项）
     * @return: boolean
     * @author: fengt
     * @date: 2021/7/21 15:08
     **/
    public boolean checkBounds(List<Long> roleIdList) {
        if (roleIdList == null || roleIdList.isEmpty()) {
            return false;
        }

        final Long userId = ShiroUtils.getUser().getId();
        if (UserConst.SUPER_USERS.contains(userId)) {
            return false;
        }

        List<Long> roles = this.getRoleIds(userId);
        if (roles.isEmpty()) {
            return true;
        } else {
            return !roles.containsAll(roleIdList);
        }
    }

}

